import os
import time
import csv
import cv2
import numpy as np
import glob
from PyQt5.QtCore import *
from PyQt5.QtWidgets import QWidget
from PyQt5.Qt import pyqtSignal
import win32file
import shutil

def is_used(file_name):
    try:
        vHandle = win32file.CreateFile(file_name, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL, None)
        return int(vHandle) == win32file.INVALID_HANDLE_VALUE
    except:
        return True
    finally:
        try:
            win32file.CloseHandle(vHandle)
        except:
            pass

class MES_FileWatcher(QWidget):
    mes_coll_sig = pyqtSignal(int)
    def __init__(self):
        super(MES_FileWatcher,self).__init__()
        self.timer = QTimer()
        self.old_len = 0
        self.old_csv_name = ''
        self.coll_num=0

    @classmethod
    def instance(cls):
        if not hasattr(MES_FileWatcher, "_instance"):
            MES_FileWatcher._instance = MES_FileWatcher()
        return MES_FileWatcher._instance

    def add_watchlist(self,MES_Folder,MES_CollectFolder,MES_Collect_Folder2):
        self.MES_Folder = MES_Folder
        self.MES_CollectFolder = MES_CollectFolder
        self.MES_CollectFolder2 = MES_Collect_Folder2

    def Start(self):
        csv_files = glob.glob(os.path.join(self.MES_Folder,"*.csv"))+glob.glob(os.path.join(self.MES_Folder,"*.txt"))
        self.old_len = len(csv_files)
        for csv_file in csv_files:
            self.old_csv_name = csv_file
            if is_used(csv_file):
                print(csv_file, 'not copy done!')
                time.sleep(0.5)
            dst_path1 = csv_file.replace(self.MES_Folder,self.MES_CollectFolder)
            dst_path2 = csv_file.replace(self.MES_Folder,self.MES_CollectFolder2)
            try:
                shutil.copyfile(csv_file,dst_path1)
                # shutil.copyfile(csv_file,dst_path2)
            except Exception as e:
                print(e)
            try:
                # shutil.copyfile(csv_file,dst_path1)
                shutil.copyfile(csv_file,dst_path2)
                self.coll_num += 1
                self.mes_coll_sig.emit(self.coll_num)
            except Exception as e:
                print(e)
        self.timerInterval = 0.1
        self.timer.timeout.connect(self.Update)
        self.timer.start(1000)

    def copy_csvs(self,csv_file):
        dst_path1 = csv_file.replace(self.MES_Folder, self.MES_CollectFolder)
        dst_path2 = csv_file.replace(self.MES_Folder, self.MES_CollectFolder2)
        try:
            shutil.copyfile(csv_file, dst_path1)
            # shutil.copyfile(csv_file,dst_path2)
        except Exception as e:
            print(e)
        try:
            # shutil.copyfile(csv_file,dst_path1)
            shutil.copyfile(csv_file, dst_path2)
        except Exception as e:
            print(e)
    def Update(self):
        csv_files = glob.glob(os.path.join(self.MES_Folder, "*.csv"))+glob.glob(os.path.join(self.MES_Folder,"*.txt"))
        file_len = len(csv_files)
        if file_len>self.old_len and file_len>1:
            # self.old_len = file_len
            # idx = file_len-self.old_len
            for i in range(self.old_len,file_len):
                self.old_csv_name = csv_files[i]
                csv_file0 = csv_files[i-1]
                if is_used(csv_file0):
                    print(csv_file0, 'not copy done!')
                    time.sleep(0.5)
                self.copy_csvs(csv_file0)
                csv_file1 = csv_files[i]
                if is_used(csv_file1):
                    print(csv_file1, 'not copy done!')
                    time.sleep(0.5)
                self.copy_csvs(csv_file1)
                self.coll_num += 1
                self.mes_coll_sig.emit(self.coll_num)
                # dst_path1 = csv_file.replace(self.MES_Folder, self.MES_CollectFolder)
                # dst_path2 = csv_file.replace(self.MES_Folder, self.MES_CollectFolder2)
                # try:
                #     shutil.copyfile(csv_file, dst_path1)
                #     shutil.copyfile(csv_file, dst_path2)
                # except Exception as e:
                #     print(e)
            self.old_len = file_len


        elif self.old_len == file_len :
            if file_len == 1:
                csv_file = csv_files[0]
                if is_used(csv_file):
                    print(csv_file, 'not copy done!')
                    time.sleep(0.5)
                self.copy_csvs(csv_file)
            elif file_len > 1:
                csv_file = csv_files[-1]

                if csv_file != self.old_csv_name:
                    csv_file0 = csv_files[-2]
                    if is_used(csv_file0):
                        print(csv_file0, 'not copy done!')
                        time.sleep(0.5)
                    self.copy_csvs(csv_file0)
                    csv_file1 = csv_files[-1]
                    if is_used(csv_file1):
                        print(csv_file1, 'not copy done!')
                        time.sleep(0.5)
                    self.copy_csvs(csv_file1)
                    self.coll_num += 1
                    self.mes_coll_sig.emit(self.coll_num)

        else:
            self.old_len = file_len

    def Stop(self):
        try:
            self.timer.stop()
        except Exception as e:
            print(e)


class MES_FileWatcher2(QWidget):
    mes_coll_sig2 = pyqtSignal(int)
    def __init__(self):
        super(MES_FileWatcher2,self).__init__()
        self.timer = QTimer()
        self.old_len = 0
        self.old_csv_name = ''
        self.coll_num = 0

    @classmethod
    def instance(cls):
        if not hasattr(MES_FileWatcher2, "_instance"):
            MES_FileWatcher2._instance = MES_FileWatcher2()
        return MES_FileWatcher2._instance

    def add_watchlist(self,MES_Folder,MES_CollectFolder,MES_Collect_Folder2):
        self.MES_Folder = MES_Folder
        self.MES_CollectFolder = MES_CollectFolder
        self.MES_CollectFolder2 = MES_Collect_Folder2

    def Start(self):
        csv_files = glob.glob(os.path.join(self.MES_Folder,"*.csv"))+glob.glob(os.path.join(self.MES_Folder,"*.txt"))
        self.old_len = len(csv_files)
        for csv_file in csv_files:
            self.old_csv_name = csv_file
            if is_used(csv_file):
                print(csv_file, 'not copy done!')
                time.sleep(0.5)
            dst_path1 = csv_file.replace(self.MES_Folder,self.MES_CollectFolder)
            dst_path2 = csv_file.replace(self.MES_Folder,self.MES_CollectFolder2)
            try:
                shutil.copyfile(csv_file, dst_path1)
                # shutil.copyfile(csv_file,dst_path2)
            except Exception as e:
                print(e)
            try:
                # shutil.copyfile(csv_file,dst_path1)
                shutil.copyfile(csv_file, dst_path2)
                self.coll_num +=1
                self.mes_coll_sig2.emit(self.coll_num)
            except Exception as e:
                print(e)
        self.timerInterval = 0.1
        self.timer.timeout.connect(self.Update)
        self.timer.start(1000)

    def copy_csvs(self,csv_file):
        dst_path1 = csv_file.replace(self.MES_Folder, self.MES_CollectFolder)
        dst_path2 = csv_file.replace(self.MES_Folder, self.MES_CollectFolder2)
        try:
            shutil.copyfile(csv_file, dst_path1)
            # shutil.copyfile(csv_file,dst_path2)
        except Exception as e:
            print(e)
        try:
            # shutil.copyfile(csv_file,dst_path1)
            shutil.copyfile(csv_file, dst_path2)
        except Exception as e:
            print(e)
    def Update(self):
        csv_files = glob.glob(os.path.join(self.MES_Folder, "*.csv"))+glob.glob(os.path.join(self.MES_Folder,"*.txt"))
        file_len = len(csv_files)
        if file_len>self.old_len and file_len>1:
            # self.old_len = file_len
            # idx = file_len-self.old_len
            for i in range(self.old_len,file_len):
                self.old_csv_name = csv_files[i]
                csv_file0 = csv_files[i-1]
                if is_used(csv_file0):
                    print(csv_file0, 'not copy done!')
                    time.sleep(0.5)
                self.copy_csvs(csv_file0)
                csv_file1 = csv_files[i]
                if is_used(csv_file1):
                    print(csv_file1, 'not copy done!')
                    time.sleep(0.5)
                self.copy_csvs(csv_file1)
                self.coll_num+=1
                self.mes_coll_sig2.emit(self.coll_num)
                # dst_path1 = csv_file.replace(self.MES_Folder, self.MES_CollectFolder)
                # dst_path2 = csv_file.replace(self.MES_Folder, self.MES_CollectFolder2)
                # try:
                #     shutil.copyfile(csv_file, dst_path1)
                #     shutil.copyfile(csv_file, dst_path2)
                # except Exception as e:
                #     print(e)
            self.old_len = file_len


        elif self.old_len == file_len :
            if file_len == 1:
                csv_file = csv_files[0]
                if is_used(csv_file):
                    print(csv_file, 'not copy done!')
                    time.sleep(0.5)
                self.copy_csvs(csv_file)
            elif file_len > 1:
                csv_file = csv_files[-1]

                if csv_file != self.old_csv_name:
                    csv_file0 = csv_files[-2]
                    if is_used(csv_file0):
                        print(csv_file0, 'not copy done!')
                        time.sleep(0.5)
                    self.copy_csvs(csv_file0)
                    csv_file1 = csv_files[-1]
                    if is_used(csv_file1):
                        print(csv_file1, 'not copy done!')
                        time.sleep(0.5)
                    self.copy_csvs(csv_file1)
                    self.coll_num += 1
                    self.mes_coll_sig2.emit(self.coll_num)

        else:
            self.old_len = file_len

    def Stop(self):
        try:
            self.timer.stop()
        except Exception as e:
            print(e)




